<?php
class AlibabaSDK {
    private $appKey;
    private $secret;
    
    public function __construct($appKey, $secret) {
        $this->appKey = $appKey;
        $this->secret = $secret;
    }
    
    private function generateSignature($apiInfo, $params) {
        // 1. 移除签名参数
        unset($params['_aop_signature']);
    
        // 3. 按字典序排序
        ksort($params);
        // 4. 构建签名字符串
        $signParams = [];
        foreach ($params as $key => $value) {
            if ($value !== '' && !is_null($value)) { // 过滤空值
                $signParams[] = $key . $value;
            }
        }
                
       // $rawQueryString = implode('&', $signParams); // 这里才是字符串
        //echo $rawQueryString;
        // 5. 拼接 API 路径和参数
        $signStr = $apiInfo . implode('', $signParams);
        //echo "签名串".$signStr;
        // 6. 生成签名
        return strtoupper(bin2hex(hash_hmac("sha1", $signStr, $this->secret, true)));
    }
    
    
    public function execute($namespace, $apiName, $params = [], $accessToken = '') {
        // 构建API路径
        $apiInfo = 'param2/1/' . $namespace . '/' . $apiName . '/' . $this->appKey;
        // 构建完整URL
        $url = 'https://gw.open.1688.com/openapi/' . $apiInfo;
        // 准备POST参数
        $postParams = [];
        $postParams['access_token'] = $accessToken;
        // 合并业务参数
        $postParams = array_merge($postParams, $params);
        // 生成签名
       $_aop_signature =  $postParams['_aop_signature'] = $this->generateSignature($apiInfo, $postParams);
        $queryString = http_build_query($postParams, '', '&', PHP_QUERY_RFC3986);

        $fullUrl = $url . '?' . $queryString;

        // 发起请求
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $fullUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/x-www-form-urlencoded' // 这里改了
            ]
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        
        if(curl_errno($ch)) {
            throw new Exception('Curl error: ' . curl_error($ch));
        }
        
        curl_close($ch);
        
        if($httpCode != 200) {
            throw new Exception('HTTP error: ' . $httpCode . ' Response: ' . $response);
        }
        
        return json_decode($response, true);
    }
} 